package com.bhs.sansong.ui.dialog;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bhs.sansong.R;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.bean.CompanyInfo;
import com.bhs.sansong.bean.RangeName;
import com.bhs.sansong.bean.RangeTransportBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.utils.MediaStoreUtils;
import com.bhs.sansong.utils.WxShareUtils;
import com.bumptech.glide.Glide;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.lxj.xpopup.impl.FullScreenPopupView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

public class SharePosterDialog extends FullScreenPopupView implements NetCallBack, View.OnClickListener {

    private ShapeableImageView mIvDoorPicture;
    private ShapeableImageView mIvFace;
    private TextView mTvCompanyName;
    private TextView mTvInfo;
    private TextView mTvLine;
    private TextView mTvPhone;
    private TextView mTvAddress;
    private ImageView mIvCode;
    private FrameLayout mFlClose;
    private TextView mTvWeChat;
    private TextView mTvCircleFriends;
    private TextView mTvSave;
    private CompanyInfo companyInfo;
    private BaseActivity activity;
    private int logistics_id;
    private LinearLayout mLlPoster;
    private FrameLayout mFlCode2;
    private ImageView mQrCode2;

    public SharePosterDialog(@NonNull BaseActivity context, CompanyInfo companyInfo, int logistics_id) {
        super(context);
        this.companyInfo = companyInfo;
        this.activity = context;
        this.logistics_id = logistics_id;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_share_poster;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        initView();
        initData();
    }

    private void initData() {
        String content = "https://saasdemo.sansongkeji.com/order?logistics_id=" + logistics_id;
        String company = "https://saasdemo.sansongkeji.com/company?logistics_id=" + logistics_id;
        activity.networkRequest(activity.netApi.getSpecialLineRange(logistics_id), this);
        Glide.with(getContext()).load(companyInfo.getCompany_pic()).into(mIvDoorPicture);
        Glide.with(getContext()).load(companyInfo.getCompany_pic()).into(mIvFace);
        mTvCompanyName.setText(companyInfo.getCompany_name());
        mTvInfo.setText(String.format("浏览量 %s 完单量 %s 收藏量 %s", companyInfo.getVisitor_count(),companyInfo.getOrder_count(),
                 companyInfo.getCollect_count()));
        mTvPhone.setText(String.format("联系电话：%s %s", companyInfo.getMobile(),
                !TextUtils.isEmpty(companyInfo.getFixed_telephone()) ? companyInfo.getFixed_telephone() : ""));
        mTvAddress.setText(String.format("公司地址：%s", companyInfo.getAddress()));
        mIvCode.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= 16) {
                    mIvCode.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    mIvCode.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                try {
                    BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
                    //HashMap设置二维码参数
                    Map map = new HashMap();
                    //   设置容错率 L>M>Q>H  等级越高扫描时间越长,准确率越高
                    map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                    //设置外边距
                    map.put(EncodeHintType.MARGIN, 1);
                    Bitmap bitmap = barcodeEncoder.encodeBitmap(content, BarcodeFormat.QR_CODE, mIvCode.getWidth(), mIvCode.getHeight(), map);
                    mIvCode.setImageBitmap(bitmap);
                } catch (Exception e) {

                }
            }
        });

        mQrCode2.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= 16) {
                    mQrCode2.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    mQrCode2.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                try {
                    BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
                    //HashMap设置二维码参数
                    Map map = new HashMap();
                    //   设置容错率 L>M>Q>H  等级越高扫描时间越长,准确率越高
                    map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                    //设置外边距
                    map.put(EncodeHintType.MARGIN, 1);
                    Bitmap bitmap = barcodeEncoder.encodeBitmap(company, BarcodeFormat.QR_CODE, mQrCode2.getWidth(), mQrCode2.getHeight(), map);
                    mQrCode2.setImageBitmap(bitmap);
                } catch (Exception e) {

                }
            }
        });
    }

    private void initView() {
        mIvDoorPicture = findViewById(R.id.iv_door_picture);
        mIvFace = findViewById(R.id.iv_face);
        mTvCompanyName = findViewById(R.id.tv_company_name);
        mTvInfo = findViewById(R.id.tv_info);
        mTvLine = findViewById(R.id.tv_line);
        mTvPhone = findViewById(R.id.tv_phone);
        mTvAddress = findViewById(R.id.tv_address);
        mIvCode = findViewById(R.id.qrCode);
        mFlClose = findViewById(R.id.fl_close);
        mTvWeChat = findViewById(R.id.tv_WeChat);
        mTvCircleFriends = findViewById(R.id.tv_circle_friends);
        mTvSave = findViewById(R.id.tv_save);
        mFlClose.setOnClickListener(this);
        mTvWeChat.setOnClickListener(this);
        mTvCircleFriends.setOnClickListener(this);
        mTvSave.setOnClickListener(this);
        mLlPoster = findViewById(R.id.ll_poster);
        mFlCode2 = findViewById(R.id.fl_code2);
        mQrCode2 = findViewById(R.id.qrCode2);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        RangeTransportBean bean = new Gson().fromJson(json, RangeTransportBean.class);
        if (bean.isStatus()) {
            StringBuilder info = new StringBuilder();
            String lineName = null;
            for (RangeName rangeName : bean.getData().getRange()) {
                for (RangeName name : rangeName.getChild()) {
                    info.append(name.getName()).append("、");
                }
            }
            if (!TextUtils.isEmpty(info)) {
                info = new StringBuilder(info.substring(0, info.toString().lastIndexOf("、")));
                lineName = info.toString();
                lineName = lineName.replace("市", "");
            }

            mTvLine.setText(String.format("热门专线：%s", lineName));
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_close:
                dismiss();
                break;
            case R.id.tv_WeChat:
                mLlPoster.setDrawingCacheEnabled(true);
                mLlPoster.buildDrawingCache();
                WxShareUtils.shareBmp(getContext(), mLlPoster.getDrawingCache());
                mLlPoster.setDrawingCacheEnabled(false);
                break;
            case R.id.tv_circle_friends:
                mLlPoster.setDrawingCacheEnabled(true);
                mLlPoster.buildDrawingCache();
                WxShareUtils.shareBmp(getContext(), mLlPoster.getDrawingCache(), SendMessageToWX.Req.WXSceneTimeline);
                mLlPoster.setDrawingCacheEnabled(false);
                break;
            case R.id.tv_save:
                // 获取图片某布局
                mLlPoster.setDrawingCacheEnabled(true);
                mLlPoster.buildDrawingCache();
                methodRequiresTwoPermission();
                break;
        }
    }

    public static final int RC_LOCATION = 1; // requestCode
    String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            MediaStoreUtils.saveImages(getActivity(), mLlPoster.getDrawingCache());
            mLlPoster.setDrawingCacheEnabled(false);
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(getActivity(), "我需要权限来保存图片", RC_LOCATION, perms);
        }
    }
}
